<?php

namespace App\Http\Controllers\Admin;

use App\Models\CompetiteActivityDatabase;
use App\Models\CompetiteActivityWorks;
use App\Models\CompetiteActivityWorksDatabase;
use App\Validate\CompetiteActivityDatabaseValidate;
use App\Validate\CompetiteActivityWorksDatabaseValidate;
use Exception;
use Illuminate\Support\Facades\DB;

/**
 * 线上大赛作品数据库（作品管理）
 */
class CompetiteActivityWorksDatabaseController extends CommonController
{

    public $model = null;
    public $competiteActivityWorks = null;
    public $validate = null;

    public function __construct()
    {
        parent::__construct();

        $this->model = new CompetiteActivityWorksDatabase();
        $this->competiteActivityWorks = new CompetiteActivityWorks();
        $this->validate = new CompetiteActivityWorksDatabaseValidate();
    }

    /**
     * 获取已收录的作品id，或电子书id
     * @param database_id int 数据库id
     * @param type 类型  1 作品id  2 电子书id 
     */
    public function filterList()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('filter_list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $condition[] = ['database_id', '=', $this->request->database_id];
        $condition[] = ['type', '=', $this->request->type];
        $field = $this->request->type == 1 ? 'works_id' : 'ebook_id';

        return $this->model->getFilterList(['id', $field], $condition);
    }

    /**
     * 列表
     * @param database_id int 数据库id
     * @param page int 当前页
     * @param limit int 分页大小
     * @param keywords string 搜索关键词(作品数据库名称)
     * @param start_time datetime 创建时间(开始)
     * @param end_time datetime 创建时间(截止)
     * @param type datetime 类型  1 作品  2 电子书
     */
    public function lists()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('list')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $database_id = $this->request->database_id;
        $type = $this->request->type;
        $page = $this->request->page ? intval($this->request->page) : 1;
        $limit = $this->request->limit ? intval($this->request->limit) : 10;
        $keywords = $this->request->keywords;
        $start_time = $this->request->start_time;
        $end_time = $this->request->end_time;

        $res = $this->model->lists($database_id, $keywords, $type, $start_time, $end_time, $limit);

        if (empty($res['data'])) {
            return $this->returnApi(203, "暂无数据");
        }
        foreach ($res['data'] as $key => $val) {
            $res['data'][$key][$this->list_index_key] = $this->addSerialNumberOne($key, $page, $limit);
        }
        $res = $this->disPageData($res);
        return $this->returnApi(200, "查询成功", "YES", $res);
    }


    /** 
     * 收录作品
     * @param database_id int 数据库id
     * @param works_ids int 作品id 多个逗号拼接
     * @param ebook_ids int 电子书id 多个逗号拼接   works_ids 与 ebook_ids 二选一，一次只能收录一种类型，但不能同时为空
     */
    public function add()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('add')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        if (empty($this->request->works_ids) && empty($this->request->ebook_ids)) {
            return $this->returnApi(202, "收录内容不能为空");
        }

        // 启动事务
        DB::beginTransaction();
        try {
            $this->model->recordAdd($this->request->all());
            // 提交事务
            DB::commit();
            return $this->returnApi(200, "收录成功", true);
        } catch (\Exception $e) {
            // 回滚事务
            DB::rollBack();
            return $this->returnApi(202, "收录失败" . $e->getMessage());
        }
    }

    /**
     * 删除收录的作品
     * @param ids int 收录id 多个逗号拼接
     */
    public function del()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('del')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }
        $res = $this->model->recordDel($this->request->ids);

        if ($res) {
            return $this->returnApi(200, "删除成功", true);
        }
        return $this->returnApi(202, $res);
    }



    /**
     * 排序
     * content json格式数据  [{"id":1,"sort":2},{"id":2,"sort":2},{"id":3,"sort":3},{"id":4,"sort":4},{"id":5,"sort":5}]   第一个 sort 最大
     */
    public function sortChange()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('sort_change')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $content = $this->request->input('content', '');
        if (empty($content)) {
            return $this->returnApi(201, "参数传递错误");
        }
        $content = json_decode($content, true);

        DB::beginTransaction();
        try {
            foreach ($content as $key => $val) {
                $this->model->where('id', $val['id'])->update(['sort' => $val['sort']]);
            }
            DB::commit();
            return $this->returnApi(200, "修改成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, $e->getMessage());
        }
    }
}
